<template>
  <div class='container'>
    <a-modal
      :width='800'
      title='配置执行周期'
      :visible='showCron'
      @cancel='showCron = false'
      :footer='null'
    >
      <vcrontab @hide='showCron = false' @fill='crontabFill' :expression='cron'></vcrontab>
    </a-modal>
    <!--  源表达式  -->
    <a-input style='display: none' v-model='cron' placeholder='请选择对应执行周期' @click.native='showCron = true' />
    <!--  展示表达式  -->
    <a-row>
      <a-col :span='20'>
        <a-input v-model='cronTranslate' type='textarea' style='height: 200px' disabled placeholder='请选择对应执行周期' />
      </a-col>
      <a-col :span='3' :offset='1'>
        <a-button @click.native='showCron = true'>选择</a-button>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import vcrontab from './v-crontab/index'

export default {
  props: {
    value: {
      type: String,
      default() {
        return ''
      }
    }
  },
  components: {
    vcrontab
  },
  computed: {},
  watch: {
    cron(val) {
      this.cronTranslate = this.getCronTranslate()
      this.$emit('change', val)
    }
  },
  data() {
    return {
      cron: '* * * * * ?',
      tabTitles: ['分', '时', '日', '月', '年'],
      cronTranslate: '',
      showCron: false
    }
  },
  methods: {
    getCronTranslate() {
      const cron = this.cron
      if (cron === '* * * * * ?') {
        return '未指定执行周期'
      }
      let cronList = cron.split(' ')
      if (cronList.length > 6) {
        cronList.pop()
      }
      if (cronList.length > 5) {
        cronList.shift()
      }
      let result = cronList.map((item, index) => {
        return this.translateCronItem(item, index)
      })
      return result.reverse().join('\n')
    },
    translateCronItem(value, index) {
      const unit = this.tabTitles[index]
      if (value === '*' || value === '?') {
        return unit + '级执行周期为：每' + unit + ','
      }
      if (!isNaN(Number(value))) {
        return unit + '级执行周期为：' + value + unit
      }
      if (~value.indexOf('/')) {
        const tempValue = value.split('/')
        return unit + '级执行周期为：从第' + tempValue[0] + unit + '开始、每' + tempValue[1] + unit
      }
      if (~value.indexOf('L')) {
        return unit + '级执行周期为：' + '最后一' + unit
      }
      if (~value.indexOf('-')) {
        const tempValue = value.split('-')
        return unit + '级执行周期为：' + tempValue[0] + unit + '至' + tempValue[1] + unit
      }
      if (~value.indexOf(',')) {
        const tempValue = value.split(',')
        return unit + '级执行周期为：' + value + unit
      }
      if (~value.indexOf('W')) {
        const tempValue = value.split('W')
        return unit + '级执行周期为：' + tempValue[0] + unit + '最近的工作日'
      }
    },
    crontabFill(value) {
      //确定后回传的值
      this.cron = value
    },
    handleCancel() {

    },
    handleOk() {

    }
  },
  created() {
    if (this.value) {
      this.cron = this.value
    }
  }
}
</script>

<style lang='less' scoped>
.container {
  width: 100%;
}
</style>